<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Data Bunker - admin / view user requests</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
    integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
  <link rel="stylesheet" href="css/bootstrap-table.min.css">
  <link rel="stylesheet" href="style.css">

  <script src="conf.js"></script>
  <script src="site.js"></script>

  <script src="js/jquery.min.js"></script>
  <script src="js/bootstrap.bundle.min.js"></script>
  <script src="js/bootstrap-table.min.js"></script>
 
  <script src="js/jdd.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" href="css/jdd.css">
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/highlight.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/languages/json.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/a11y-dark.min.css">

  <script>
    var xtoken = window.localStorage.getItem('xtoken');
    function displayTargetObject(target, row, index) {
      if (row.mode) {
        return '(' + row.mode + ') ' + target;
      }
      return target;
    }
    function displayActivity(action, row, index) {
      var info = '';
      if (row.brief) {
        info = '(' + row.brief + ') ';
      }
      if (row.app) {
        info = '(' + row.app + ') ';
      }
      result = '';
      if (row.status && row.status == "open") {
        result = '<i class="fas fa-question"></i>&nbsp;' + info + action;
      } else if (row.status && row.status == "canceled") {
        result = '<i class="fas fa-times"></i>&nbsp;' + info + action;
      } else {
        result = '<i class="fas fa-check"></i>&nbsp;' + info + action;
      }
      return result;
    }
    function displayDrillDownLink(rtoken, row, index) {
      //console.log(row);
      var links = '<a href=\'javascript:displayRequest(\"' + rtoken +
        '\");\'>view</a>&nbsp;|&nbsp;';
      if (row["action"] == "forget-me") {
        links += '<a href=\'javascript:enquireReason(\"approve\",\"' + rtoken +
          '\");\'>approve & delete</a>&nbsp;|&nbsp;';
      } else if (row["action"] == "consent-withdraw") {
        links += '<a href=\'javascript:enquireReason(\"approve\",\"' + rtoken +
          '\");\'>approve & withdraw</a>&nbsp;|&nbsp;';
      } else {
        links += '<a href=\'javascript:enquireReason(\"approve\",\"' + rtoken +
          '\");\'>approve</a>&nbsp;|&nbsp;';
      }
      links += '<a href=\'javascript:enquireReason(\"cancel\",\"' + rtoken +
          '\");\'>reject</a>';
      return links;
    }
    var modalPopup;

    function enquireReason(action, request) {
        var title0 = "Specify a reason";
        var form = `<form><div class="form-group row">
          <label for="reason" class="col-sm-3 col-form-label">Reason</label>
          <div class="col-sm-9"><textarea class="form-control" id="reason" rows="2"></textarea>
          </div></div></form>`;
	var bTitle = 'Approve';
	if (action == "cancel") {
          bTitle = 'Reject';
	}
        var btn = `<button type="submit" class="btn btn-primary" id="submitButton">`+bTitle+`</button>`;
        var modal = showForm(title0, form, btn);
        modal.find('#submitButton').click(function (event) {
	  modal.modal('hide');
          var reason = modal.find('#reason').val();
          if (action == "cancel") {
            cancelRequest(request, reason);
	  } else {
            approveRequest(request, reason);
	  }
        });
    }

    function approveRequest(request, reason) {
      var msg = {};
      msg["reason"] = reason;
      var xhr = new XMLHttpRequest();
      xhr.open('POST', "/v1/request/" + request);
      xhr.setRequestHeader("X-Bunker-Token", xtoken)
      xhr.setRequestHeader('Content-type', 'application/json');
      xhr.onload = function () {
        if (xhr.status === 200) {
          document.location.reload();
        } else if (xhr.status > 400 && xhr.status < 500) {
          //alert("error, try again");
          document.location = "/";
        }
      }
      xhr.send(JSON.stringify(msg));
    }

    function cancelRequest(request, reason) {
      var msg = {};
      msg["reason"] = reason;
      var xhr = new XMLHttpRequest();
      xhr.open('DELETE', "/v1/request/" + request);
      xhr.setRequestHeader("X-Bunker-Token", xtoken);
      xhr.setRequestHeader('Content-type', 'application/json');
      xhr.onload = function () {
        if (xhr.status === 200) {
          document.location.reload();
        } else if (xhr.status > 400 && xhr.status < 500) {
          //alert("error, try again");
          document.location = "/";
        }
      }
      xhr.send(JSON.stringify(msg));
    }

    function displayRequest(rtoken) {
      var xhr0 = new XMLHttpRequest();
      // first save consent
      xhr0.open('GET', '/v1/request/' + rtoken, false);
      xhr0.setRequestHeader("X-Bunker-Token", xtoken)
      xhr0.setRequestHeader('Content-type', 'application/json');
      xhr0.onload = function () {
        if (xhr0.status === 200) {
          var data = JSON.parse(xhr0.responseText);
          if (data.status == "ok") {
            var d = JSON.stringify(data, null, 4);
            setTimeout(function () {
              if (data["original"] && data["change"]) {
                var code = '<div class="diffcontainer"><div id="report"></div>'+
			   '<pre id="out" class="left" class="codeBlock"></pre>'+
		           '<pre id="out2" class="right" class="codeBlock"></pre>'+
			   '</div>';
                $('#drilldown').html(code);
                jdd.compare(data["original"], data["change"]);
              } else {
                $('#drilldown').html('<pre><code class="json">' + d + '</code></pre>');
                document.querySelectorAll('pre code').forEach((block) => {
                  hljs.highlightBlock(block);
                });
              }
            }, 300);
          }
        }
      }
      xhr0.send();

      var heading = "Drill-down report";
      var text = "Display event: " + rtoken;
      var cancelButtonTxt = "Close popup";
      if (modalPopup) {
        $('#request-event-text').text(text)
        modalPopup.modal('show');
        return;
      }
      modalPopup =
        $('<div class="modal fade" role="dialog"><div class="modal-dialog" role="document" style="max-width: 80%;"><div class="modal-content">' +
          '<div class="modal-header">' +
          '<h5 class="modal-title">' + heading + '</h5>' +
          '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
          '<span aria-hidden="true">&times;</span></button>' +
          '</div>' +
          '<div class="modal-body">' +
          '<p id="request-event-text">' + text + '</p>' +
          '<div id="drilldown"></div>' +
          '</div>' +
          '<div class="modal-footer">' +
          '<a href="#" class="btn" data-dismiss="modal">' +
          cancelButtonTxt +
          '</a>' +
          '</div>' +
          '</div></div></div>');
      modalPopup.find('#okButton').click(function (event) {
        modalPopup.modal('hide');
      });
      modalPopup.modal('show');
      modalPopup.on('hidden.bs.modal', function() {
        $('#drilldown').html(null);
      });
    }

    $(function () {
      showAdminMenu();
      $('#table').bootstrapTable({
        /*data: mydata */
        url: "/v1/requests",
        undefinedText: 'n/a',
        /* url: "data1.json", */
        method: "GET",
        ajaxOptions: {
          headers: { "X-Bunker-Token": xtoken },
          crossDomain: true
        },
        showExtendedPagination: true,
        sidePagination: "server",
        pagination: true,
        search: false,
        classes: "table",
        onLoadError: function (status, res) {
          console.log(status);
          if (status > 400 && status < 500) {
            document.location = "/";
          }
        }
      });
    });
  </script>
<style>
textarea {min-height:auto;}
</style>
</head>

<body>
  <div class="container">
    <div class="row col-md-12">
      <div style="width:100%;">
        <nav class="navbar navbar-expand-lg navbar-dark bg-secondary">
          <a class="navbar-brand" href="#">Admin</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <ul id="admin-menu" class="navbar-nav">
            </ul>
          </div>
        </nav>
      </div>
      <div class="bigblock">
        <h4>User requests</h4>
        <p id="msg">A list of all user outstanding requests.</p>
        <table id="table" class="table">
          <thead>
            <tr>
              <th scope="col-4" data-field="action" data-formatter="displayActivity">Request name</th>
              <th scope="col-2" data-field="when" data-formatter="dateFormat">Time</th>
              <th scope="col-2" data-field="token" data-formatter="displayTargetObject">User token</th>
              <th scope="col-2" data-field="status">Status</th>
              <th scope="col-2" data-field="rtoken" data-formatter="displayDrillDownLink">Actions</th>
            </tr>
          </thead>
        </table>
      </div>
    </div>
  </div>
</body>

</html>
